package com.shuai.starter.bootstrap;

import com.shuai.frame.config.XSRpcApplicationContext;
import com.shuai.frame.config.XSRpcConfig;
import com.shuai.frame.factory.RegistryFactory;
import com.shuai.frame.model.ServiceMetaInfo;
import com.shuai.frame.registry.LocalRegister;
import com.shuai.frame.registry.RegistryCenter;
import com.shuai.starter.annotation.RpcProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.concurrent.ExecutionException;

/**
 * @author bxs
 * @version 1.0
 * @Date 2024/7/31
 */
@Slf4j
public class RpcProviderBootstrap implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        RpcProvider annotation = bean.getClass().getAnnotation(RpcProvider.class);
        if (annotation == null) {
            return bean;
        }
        Class<?> aClass = annotation.interfaceClass();
        if (aClass == void.class) {
            aClass = bean.getClass().getInterfaces()[0];
        }
        XSRpcConfig xsRpConfig = XSRpcApplicationContext.getXSRpConfig();
        ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
        serviceMetaInfo.setServiceName(aClass.getName());
        serviceMetaInfo.setServiceVersion(annotation.version());
        serviceMetaInfo.setServiceHost(xsRpConfig.getServerAddress());
        serviceMetaInfo.setServicePort(xsRpConfig.getServerPort());
        serviceMetaInfo.setServiceDesc(annotation.desc());
        // 本地注册
        LocalRegister.register(aClass.getName(), bean.getClass());
        // 远程注册
        RegistryCenter registryCenter = RegistryFactory.getRegistryCenter(xsRpConfig.getRegistryCenterConfig().getRegistryType());
        try {
            registryCenter.register(serviceMetaInfo);
        } catch (ExecutionException | InterruptedException e) {
            log.error("服务{}注册失败！注册中心配置异常 ", serviceMetaInfo.getServiceName());
            throw new RuntimeException("服务注册失败！注册中心配置异常 ", e);
        }
        log.info("服务{}注册成功！", serviceMetaInfo.getServiceName());
        return bean;
    }
}
